package presentation.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import persistence.Supplier;
import business.BusinessObjectAssembler;
import business.SubscriptionLogic;
import business.exception.BusinessException;

public class SupplierConverter implements Converter {
	
	private static SubscriptionLogic subscriptionLogic;
	
	static {
		subscriptionLogic = BusinessObjectAssembler.getSubscriptionLogic();
	}

	@Override
	public Object getAsObject(FacesContext fctx, UIComponent comp, String value)
			throws ConverterException {
		Supplier supplier = null;
		if (value != null && ConverterUtil.isNumber(value)) {
			try {
				supplier = subscriptionLogic.getSupplierById(Integer.valueOf(value));
			}
			catch(BusinessException be) {
				throw new ConverterException(be);
			}
		}
		return supplier;
	}

	@Override
	public String getAsString(FacesContext fctx, UIComponent comp, Object value)
			throws ConverterException {
		String retVal = null;
		Supplier supplier = (Supplier)value;
		if (supplier != null)
			retVal = String.valueOf(supplier.getId());
		return retVal;
	}

}